/*
 * Created on Feb 26, 2005
 */
package com.scalar.chiptrack.finance.openpo.actioncommands;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.Iterator;
import java.text.DecimalFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackExtendedAction;

import com.scalar.chiptrack.finance.openpo.ReceivingLineItem;
import com.scalar.chiptrack.finance.openpo.ReceivingLineItemList;
import com.scalar.chiptrack.finance.openpo.PurchaseOrderLineItem;
import com.scalar.chiptrack.finance.openpo.dao.PurchaseOrderDAO;
import com.scalar.chiptrack.finance.openpo.forms.PurchaseOrderReceiptForm;
import com.scalar.chiptrack.users.ErrorReport;
import com.scalar.chiptrack.utils.Logger;


/**
 * @author Ravikanth
**/
public class PurchaseOrderReceiptConfirmCommand extends ChipTrackExtendedAction
{
	/* 
	 * Purchase Order Receipt Confirm Command
	 */
	public ActionForward executeRequest( ActionMapping mapping,	ActionForm form, HttpServletRequest request, HttpServletResponse response)throws Exception
	{
		HashMap errors              = new HashMap();
		HashMap info                = new HashMap();
		PurchaseOrderReceiptForm purchaseOrderReceiptForm = ( PurchaseOrderReceiptForm ) form;
		String actionForward 		= "receiptSearch";
		HttpSession mSession 		= request.getSession();
        ArrayList poTaxTypes = (ArrayList) request.getAttribute("poTaxTypes");

		try
		{
			if( purchaseOrderReceiptForm  != null)
			{
                String poTaxType = purchaseOrderReceiptForm.getPoTaxType();
                if( poTaxType != null )
                {
                    poTaxType = poTaxType.trim();
                    if( "-1".equals(poTaxType))
                    {
                        String newPoTaxState = purchaseOrderReceiptForm.getNewPoState();
                        boolean newPoTaxStateExists = PurchaseOrderDAO.doesPOTaxStateExist( null, newPoTaxState);
                        if( !newPoTaxStateExists )
                        {
                            String tax = purchaseOrderReceiptForm.getNewPoTax();
                            PurchaseOrderDAO.savePOTax( newPoTaxState, tax );
                            purchaseOrderReceiptForm.setPoTaxType( newPoTaxState);
                        }
                        else
                        {
                            purchaseOrderReceiptForm.setPoTaxType( null);
                            errors.put("The State '" + newPoTaxState + "' already exists", null);
                        }
                    }
                }
                PurchaseOrderDAO.loadLineItemPrice( null, purchaseOrderReceiptForm.getReceivingLineItemList() );
                Iterator lineItemIterator = purchaseOrderReceiptForm.getReceivingLineItemList().iterator();
                while ( lineItemIterator.hasNext() )
                {
                    ReceivingLineItem receivingLineItem = (ReceivingLineItem) lineItemIterator.next();
                    if ( receivingLineItem.isSelected() && receivingLineItem.getUnitCost() == 0 && receivingLineItem.getProcessStepId() > 0 )
                    {
                        errors.put( "Unit Cost should be valid number and first digit can not be space or zero for LineItem " + receivingLineItem.getPurchaseOrderLineItemNumber(), null );
                    }
                }
                setExtendedPriceAndTotals( purchaseOrderReceiptForm );
                if( errors.isEmpty() )
                {
				    actionForward = "view";
                    String searchType = request.getParameter("searchType");
                    if( searchType == null )
                    {
                        searchType = "";
                    }
                    request.setAttribute( "searchType", searchType);
                }
                else
                {
                    actionForward = "receipt";
                }
                request.setAttribute("poTaxTypes", PurchaseOrderDAO.loadPOTaxesList() );
			}
			else
			{
				throw new ScalarException( ERROR_LOADING_RECEIVINGS_TRANSACTION_INFORMATION, null );
			}
		}
		catch ( Exception e )
		{
			Logger.error( ERROR_LOADING_RECEIVINGS_TRANSACTION_INFORMATION, e );
			errors.put( ERROR_INTERNAL_SERVER_ERROR, ERROR_LOADING_RECEIVINGS_TRANSACTION_INFORMATION );
			mSession.setAttribute( ERROR_REPORT_OBJECT, new ErrorReport( ERROR_LOADING_RECEIVINGS_TRANSACTION_INFORMATION, e ) );
			actionForward = "receiptSearch";
			request.setAttribute( "vendorsList", PurchaseOrderDAO.loadAllVendors() );
			request.setAttribute( "yearList", PurchaseOrderDAO.getYearList () );
			request.setAttribute( "productList", PurchaseOrderDAO.loadPOProductsList() );
		}

		request.setAttribute( ERROR_MESSAGES, errors );
		request.setAttribute( INFO_MESSAGES, info );
        saveToken( request );
        return mapping.findForward( actionForward );
	}

	/**
	 * @param purchaseOrderReceiptForm
	 */
	public static void setExtendedPriceAndTotals(PurchaseOrderReceiptForm purchaseOrderReceiptForm)
	{
		double sub_total = 0.0;
        ReceivingLineItemList receivingLineItemList = null;
		ReceivingLineItem recevingLineItem = null;
        DecimalFormat formatter = new DecimalFormat("#.##");

		if( purchaseOrderReceiptForm != null )
		{
			receivingLineItemList = purchaseOrderReceiptForm.getReceivingLineItemList();
			if( receivingLineItemList != null )
			{
				for( int i = 0; i < receivingLineItemList.size(); i++ )
				{
					recevingLineItem = (ReceivingLineItem)receivingLineItemList.get(i);
					
					try
					{
                        String output = formatter.format(recevingLineItem.getUnitCost() * recevingLineItem.getShippedQty());
						recevingLineItem.setExtendedCost( Double.parseDouble( output) );
						sub_total = sub_total + recevingLineItem.getExtendedCost(); 	
					}
					catch( Exception e )
					{
						recevingLineItem.setExtendedCost( 0.0 );
					}
				}
				purchaseOrderReceiptForm.setSub_total( Double.parseDouble( formatter.format(sub_total) ) );
			}
			
			try
			{
                String poTaxType = purchaseOrderReceiptForm.getPoTaxType();
                double tax = 0.0;
                if( poTaxType != null )
                {
                    if( !("0".equals( poTaxType )) )
                    {
                        double newTaxPercent = PurchaseOrderDAO.getTaxValue( poTaxType );
                        String output = formatter.format(sub_total*( newTaxPercent/100 ));
					    tax =  Double.parseDouble( output);
                        purchaseOrderReceiptForm.setTax( tax);
                    }
                }

                String output = formatter.format( purchaseOrderReceiptForm.getSub_total() + purchaseOrderReceiptForm.getFrieght() + tax + purchaseOrderReceiptForm.getMiscellaneous() - purchaseOrderReceiptForm.getTrade_Discount() );
				purchaseOrderReceiptForm.setTotal( Double.parseDouble( output) );
			}
			catch( Exception e )
			{
				purchaseOrderReceiptForm.setTotal( 0.0 );
			}
		}	
	}
}
